/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package GUI;

import Enum.TrangThaiDonHangEnum;
import dao.CuaHangDAO;
import dao.HoaDonDAO;
import dao.TrangThaiDonHangDAO;
import java.awt.Component;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import javax.swing.DefaultListCellRenderer;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;
import org.apache.log4j.Logger;
import pojo.CuaHang;
import pojo.HoaDon;
import pojo.TrangThaiDonHang;

/**
 *
 * @author softviet
 */
public class DanhSachHoaDonGUI extends javax.swing.JPanel {

    /**
     * Creates new form DanhSachHoaDonGUI
     */
    private List<HoaDon> hoaDons;
    private static Logger logger = Logger.getLogger(DanhSachHoaDonGUI.class);

    public DanhSachHoaDonGUI() throws Exception {
        initComponents();
        FormatControls();
        AutoLoad();
    }

    private void FormatControls() {
        Utility.FormatNumberStringTextfield(txtMaHoaDon);
    }

    private void AutoLoad() throws Exception {
        List<CuaHang> cuaHangs = (List<CuaHang>) CuaHangDAO.LayDanhSach(CuaHang.class, MainGUI.nguoiDung);
        Collections.sort(cuaHangs, new Comparator<CuaHang>() {
            @Override
            public int compare(CuaHang o1, CuaHang o2) {
                return o1.getTenCuaHang().compareTo(o2.getTenCuaHang());
            }
        });
        Utility.SetDataSourceInCombo(cuaHangs, cboCuaHang);
        cboCuaHang.setRenderer(new DefaultListCellRenderer() {
            @Override
            public Component getListCellRendererComponent(JList<?> list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
                super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
                if (value instanceof CuaHang) {
                    CuaHang cuaHang = (CuaHang) value;
                    setText(cuaHang.getTenCuaHang());
                }
                return this;
            }
        });
        cboCuaHang.setSelectedIndex(-1);

        List<TrangThaiDonHang> trangThaiDonHangs = (List<TrangThaiDonHang>) TrangThaiDonHangDAO.LayDanhSach(TrangThaiDonHang.class, MainGUI.nguoiDung);
        Collections.sort(trangThaiDonHangs, new Comparator<TrangThaiDonHang>() {
            @Override
            public int compare(TrangThaiDonHang o1, TrangThaiDonHang o2) {
                return o1.getTenTrangThaiDonHang().compareTo(o2.getTenTrangThaiDonHang());
            }
        });
        Utility.SetDataSourceInCombo(trangThaiDonHangs, cboTrangThaiDonHang);
        cboTrangThaiDonHang.setRenderer(new DefaultListCellRenderer() {
            @Override
            public Component getListCellRendererComponent(JList<?> list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
                super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
                if (value instanceof TrangThaiDonHang) {
                    TrangThaiDonHang trangThaiDonHang = (TrangThaiDonHang) value;
                    setText(trangThaiDonHang.getTenTrangThaiDonHang());
                }
                return this;
            }
        });
        cboTrangThaiDonHang.setSelectedIndex(-1);

        hoaDons = (List<HoaDon>) HoaDonDAO.LayDanhSach(HoaDon.class, MainGUI.nguoiDung);
        Utility.CreateColumnsFromDB(HoaDon.class, hoaDons, tbDanhSachHoaDon, new String[]{"Mã hoá đơn", "Khách hàng", "Ngày lập hoá đơn", "Tổng tiền", "Cửa hàng", "Trạng thái hoá đơn"}, null);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        txtMaHoaDon = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        txtTenKhachHang = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        dtNgayLapHoaDonFrom = new org.jdesktop.swingx.JXDatePicker();
        jLabel4 = new javax.swing.JLabel();
        dtNgayLapHoaDonTo = new org.jdesktop.swingx.JXDatePicker();
        jLabel5 = new javax.swing.JLabel();
        cboCuaHang = new javax.swing.JComboBox();
        jLabel6 = new javax.swing.JLabel();
        cboTrangThaiDonHang = new javax.swing.JComboBox();
        btnTimKiem = new javax.swing.JButton();
        btnLapHoaDon = new javax.swing.JButton();
        btnHuyHoaDon = new javax.swing.JButton();
        btnXemChiTiet = new javax.swing.JButton();
        btnClear = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        tbDanhSachHoaDon = new org.jdesktop.swingx.JXTable();

        jLabel1.setText("Mã hoá đơn");

        jLabel2.setText("Tên khách hàng");

        jLabel3.setText("Ngày lập hoá đơn từ");

        jLabel4.setText("đến");

        jLabel5.setText("Cửa hàng");

        jLabel6.setText("Trạng thái đơn hàng");

        btnTimKiem.setText("Tìm kiếm");
        btnTimKiem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnTimKiemActionPerformed(evt);
            }
        });

        btnLapHoaDon.setText("Lập hoá đơn");
        btnLapHoaDon.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnLapHoaDonActionPerformed(evt);
            }
        });

        btnHuyHoaDon.setText("Huỷ hoá đơn");
        btnHuyHoaDon.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnHuyHoaDonActionPerformed(evt);
            }
        });

        btnXemChiTiet.setText("Xem chi tiết");
        btnXemChiTiet.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnXemChiTietActionPerformed(evt);
            }
        });

        btnClear.setText("Clear");
        btnClear.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnClearActionPerformed(evt);
            }
        });

        tbDanhSachHoaDon.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {

            }
        ));
        tbDanhSachHoaDon.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                tbDanhSachHoaDonMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(tbDanhSachHoaDon);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jLabel2)
                                    .addComponent(jLabel1))
                                .addGap(40, 40, 40)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(txtMaHoaDon)
                                    .addComponent(txtTenKhachHang)))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel3)
                                .addGap(18, 18, 18)
                                .addComponent(dtNgayLapHoaDonFrom, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(18, 18, 18)
                                .addComponent(jLabel4)
                                .addGap(18, 18, 18)
                                .addComponent(dtNgayLapHoaDonTo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                        .addGap(48, 48, 48)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel6)
                            .addComponent(jLabel5))
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(cboCuaHang, 0, 183, Short.MAX_VALUE)
                            .addComponent(cboTrangThaiDonHang, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(151, 151, 151)
                        .addComponent(btnTimKiem)
                        .addGap(18, 18, 18)
                        .addComponent(btnLapHoaDon)
                        .addGap(18, 18, 18)
                        .addComponent(btnXemChiTiet)
                        .addGap(18, 18, 18)
                        .addComponent(btnHuyHoaDon)
                        .addGap(18, 18, 18)
                        .addComponent(btnClear)))
                .addContainerGap(103, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(txtMaHoaDon, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel5)
                    .addComponent(cboCuaHang, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(txtTenKhachHang, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel6)
                    .addComponent(cboTrangThaiDonHang, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(dtNgayLapHoaDonFrom, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel4)
                    .addComponent(dtNgayLapHoaDonTo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnTimKiem)
                    .addComponent(btnLapHoaDon)
                    .addComponent(btnHuyHoaDon)
                    .addComponent(btnXemChiTiet)
                    .addComponent(btnClear))
                .addGap(18, 18, 18)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 398, Short.MAX_VALUE))
        );
    }// </editor-fold>//GEN-END:initComponents

    private void btnClearActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnClearActionPerformed
        // TODO add your handling code here:
        Utility.ClearControlInPanel(this);
    }//GEN-LAST:event_btnClearActionPerformed

    private void btnTimKiemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnTimKiemActionPerformed
        try {
            // TODO add your handling code here:
            Integer maHoaDon = null;
            if (!txtMaHoaDon.getText().isEmpty()) {
                maHoaDon = Integer.parseInt(txtMaHoaDon.getText());
            }
            CuaHang cuaHang = (CuaHang) cboCuaHang.getModel().getSelectedItem();
            TrangThaiDonHang trangThaiDonHang = (TrangThaiDonHang) cboTrangThaiDonHang.getModel().getSelectedItem();
            Integer idCuaHang = null;
            if (cuaHang != null) {
                idCuaHang = cuaHang.getId();
            }
            Integer idTrangThaiDonHang = null;
            if (trangThaiDonHang != null) {
                idTrangThaiDonHang = trangThaiDonHang.getId();
            }
            hoaDons = HoaDonDAO.TimKiem(maHoaDon, txtTenKhachHang.getText().trim(), dtNgayLapHoaDonFrom.getDate(), dtNgayLapHoaDonTo.getDate(), idCuaHang, idTrangThaiDonHang, MainGUI.nguoiDung);
            Utility.CreateColumnsFromDB(HoaDon.class, hoaDons, tbDanhSachHoaDon, new String[]{"Mã hoá đơn", "Khách hàng", "Ngày lập hoá đơn", "Tổng tiền", "Cửa hàng", "Trạng thái hoá đơn"}, null);
            if (hoaDons.isEmpty()) {
                JOptionPane.showMessageDialog(this, "Không tìm thấy");
            }
        } catch (Exception ex) {
            logger.error(new Date().toString(), ex);
            JOptionPane.showMessageDialog(this, ex.getMessage());
        }
    }//GEN-LAST:event_btnTimKiemActionPerformed

    private void btnLapHoaDonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnLapHoaDonActionPerformed
        try {
            // TODO add your handling code here:
            HoaDonGUI hoaDonGUI = new HoaDonGUI(null, true,new HoaDon());
            final int x = (((JFrame) SwingUtilities.getAncestorOfClass(JFrame.class, this)).getWidth() - hoaDonGUI.getWidth()) / 2;
            final int y = (((JFrame) SwingUtilities.getAncestorOfClass(JFrame.class, this)).getHeight() - hoaDonGUI.getHeight()) / 2;
            hoaDonGUI.setLocation(x, y);
            hoaDonGUI.setButtonLuuClickedListener(new MyEventListener() {

                @Override
                public void myEventOccured(Object evt) {
                    HoaDon hoaDon=(HoaDon) evt;
                    if(hoaDon!=null){
                        hoaDons.add(hoaDon);
                        Utility.CreateColumnsFromDB(HoaDon.class, hoaDons, tbDanhSachHoaDon, new String[]{"Mã hoá đơn", "Khách hàng", "Ngày lập hoá đơn", "Tổng tiền", "Cửa hàng", "Trạng thái hoá đơn"}, null);
                        tbDanhSachHoaDon.changeSelection(tbDanhSachHoaDon.getModel().getRowCount()-1, 0, false, false);
                    }
                }
            });
            hoaDonGUI.setVisible(true);
        } catch (Exception ex) {
            logger.error(new Date().toString(), ex);
            JOptionPane.showMessageDialog(this, ex.getMessage());
        }
    }//GEN-LAST:event_btnLapHoaDonActionPerformed

    private void btnXemChiTietActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnXemChiTietActionPerformed
        // TODO add your handling code here:
        List<HoaDon> tempList=(List<HoaDon>) Utility.GetSelectedRows(tbDanhSachHoaDon, hoaDons);
        if(!tempList.isEmpty()){
            try {
                int index=hoaDons.indexOf(tempList.get(0));
                HoaDonGUI hoaDonGUI = new HoaDonGUI(null, true,tempList.get(0));
                final int x = (((JFrame) SwingUtilities.getAncestorOfClass(JFrame.class, this)).getWidth() - hoaDonGUI.getWidth()) / 2;
                final int y = (((JFrame) SwingUtilities.getAncestorOfClass(JFrame.class, this)).getHeight() - hoaDonGUI.getHeight()) / 2;
                hoaDonGUI.setLocation(x, y);
                hoaDonGUI.setVisible(true);
                Utility.CreateColumnsFromDB(HoaDon.class, hoaDons, tbDanhSachHoaDon, new String[]{"Mã hoá đơn", "Khách hàng", "Ngày lập hoá đơn", "Tổng tiền", "Cửa hàng", "Trạng thái hoá đơn"}, null);
                tbDanhSachHoaDon.changeSelection(index, 0, false, false);
            } catch (Exception ex) {
                logger.error(new Date().toString(), ex);
                JOptionPane.showMessageDialog(this, ex.getMessage());
            }
        }
        else{
            JOptionPane.showMessageDialog(this, "Xin chọn dữ liệu trên lưới để xem chi tiết");
        }
    }//GEN-LAST:event_btnXemChiTietActionPerformed

    private void btnHuyHoaDonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnHuyHoaDonActionPerformed
        // TODO add your handling code here:
        List<HoaDon> tempList=(List<HoaDon>) Utility.GetSelectedRows(tbDanhSachHoaDon, hoaDons);
        if(!tempList.isEmpty()){
            for(HoaDon hoaDon:tempList){
                if(hoaDon.getTrangThaiDonHang().getId()==TrangThaiDonHangEnum.DaThanhToan.getCode() || hoaDon.getTrangThaiDonHang().getId()==TrangThaiDonHangEnum.ThanhToanMotPhan.getCode()){
                    JOptionPane.showMessageDialog(this, "Có hoá đơn đã thanh toán hay thanh toán một phần được chọn nên không thể huỷ");
                    return;
                }
                if(JOptionPane.showConfirmDialog(this, "Bạn có chắc muốn huỷ không?","Question",JOptionPane.YES_NO_OPTION)==0){
                    try {
                        HoaDonDAO.HuyHoaDon(hoaDons);
                        Utility.RemoveSelectedRows(HoaDon.class, tbDanhSachHoaDon, hoaDons, new String[]{"Mã hoá đơn", "Khách hàng", "Ngày lập hoá đơn", "Tổng tiền", "Cửa hàng", "Trạng thái hoá đơn"}, null);
                        JOptionPane.showMessageDialog(this, "Huỷ thành công");
                    } catch (Exception ex) {
                        logger.error(new Date().toString(), ex);
                        JOptionPane.showMessageDialog(this, ex.getMessage());
                    }
                }
            }
        }
        else{
            JOptionPane.showMessageDialog(this, "Xin chọn dữ liệu trên lưới để huỷ");
        }
    }//GEN-LAST:event_btnHuyHoaDonActionPerformed

    private void tbDanhSachHoaDonMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tbDanhSachHoaDonMouseClicked
        // TODO add your handling code here:
        if(evt.getClickCount()==2){
            btnXemChiTietActionPerformed(null);
        }
    }//GEN-LAST:event_tbDanhSachHoaDonMouseClicked

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnClear;
    private javax.swing.JButton btnHuyHoaDon;
    private javax.swing.JButton btnLapHoaDon;
    private javax.swing.JButton btnTimKiem;
    private javax.swing.JButton btnXemChiTiet;
    private javax.swing.JComboBox cboCuaHang;
    private javax.swing.JComboBox cboTrangThaiDonHang;
    private org.jdesktop.swingx.JXDatePicker dtNgayLapHoaDonFrom;
    private org.jdesktop.swingx.JXDatePicker dtNgayLapHoaDonTo;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JScrollPane jScrollPane1;
    private org.jdesktop.swingx.JXTable tbDanhSachHoaDon;
    private javax.swing.JTextField txtMaHoaDon;
    private javax.swing.JTextField txtTenKhachHang;
    // End of variables declaration//GEN-END:variables
}
